<template>
    <el-container>
        <el-header><navigation :comments="comments" /></el-header>
        <el-main>
            <el-table :data="tableData.data" style="width: 100%">
                <el-table-column label="序号" width="80" type="index">
                </el-table-column>
                <el-table-column label="图书名称" prop="bookName">
                </el-table-column>
                <el-table-column label="图书类型" prop="typeName">
                </el-table-column>
                <el-table-column label="作者" prop="author">
                </el-table-column>
                <el-table-column label="出版社" prop="press">
                </el-table-column>
                <el-table-column label="价格" prop="price">
                </el-table-column>
                <el-table-column label="国际标准书号" prop="isbn">
                </el-table-column>
                <el-table-column label="创建时间" prop="createTime">
                </el-table-column>
                <el-table-column align="right" width="180">
                    <template #header>
                        <el-input v-model="search" size="mini" placeholder="输入关键字搜索" @change="search"/>
                    </template>
                    <template #default="scope">
                        <el-button size="mini" @click="handleEdit(scope.row)">Edit</el-button>
                        <el-button size="mini" type="danger" @click="handleDelete(scope.row)">Delete</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-col :span="12" :offset="6" style="margin-top: 20px">
                <!-- 分页 -->
                <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                    :current-page="pageData.currentPage" :page-sizes="[5, 10, 15, 20]" :page-size="pageData.pageSize"
                    layout="total, sizes, prev, pager, next, jumper" :total="pageData.total">
                </el-pagination>
            </el-col>
        </el-main>
    </el-container>
    <el-dialog :title="editBook.tips" v-model="editBook.dialogVisible" width="40%" :before-close="handleClose">
        <el-form :model="editBook.form">
            <el-form-item label="图书编号" :label-width="formLabelWidth" :disabled="disabled">
                <el-input v-model="editBook.form.id" autocomplete="off" disabled />
            </el-form-item>
            <el-form-item label="图书名称" :label-width="formLabelWidth">
                <el-input v-model="editBook.form.bookName" autocomplete="off" />
            </el-form-item>
            <el-form-item label="图书类型" :label-width="formLabelWidth">
                <el-select v-model="editBook.form.typeName" class="m-2">
                    <el-option v-for="item in options" :label="item.typeName" :value="item.typeName" />
                </el-select>
            </el-form-item>
            <el-form-item label="作者" :label-width="formLabelWidth">
                <el-input v-model="editBook.form.author" autocomplete="off" />
            </el-form-item>
            <el-form-item label="出版社" :label-width="formLabelWidth">
                <el-input v-model="editBook.form.press" autocomplete="off" />
            </el-form-item>
            <el-form-item label="价格" :label-width="formLabelWidth">
                <el-input v-model="editBook.form.price" autocomplete="off" />
            </el-form-item>
            <el-form-item label="国际标准书号" :label-width="formLabelWidth">
                <el-input v-model="editBook.form.isbn" autocomplete="off" />
            </el-form-item>
            <el-form-item label="封面" :label-width="formLabelWidth">
                <el-avatar shape="square" :size="100" :fit="fit" :src=editBook.form.image />
                <el-upload class="avatar-uploader" action="http://localhost:8080/upload" :show-file-list="false"
                    :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                    <img v-if="editBook.imageUrl" :src="editBook.imageUrl" class="avatar" />
                    <el-icon v-else class="avatar-uploader-icon">
                        <Plus />
                    </el-icon>
                </el-upload>
            </el-form-item>
            <el-form-item label="内容简介" :label-width="formLabelWidth">
                <el-input v-model="editBook.form.content" :rows="3" type="textarea" />
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="editBook.dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="modify">提交</el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script>
import navigation from './Navigation.vue'
import axios from 'axios'
export default {
    name: 'userTable',
    components: {
        navigation,
        axios
    },
    data() {
        return {
            comments: [
                '图书管理',
                '图书列表'
            ],
            tableData: {
                data: [],
                id: '',
                typeName: ''
            },
            loading: true,
            search: '',
            pageData: {
                total: '',
                currentRow: '',
                multipleSelection: [],
                currentPage: 1,
                pageSize: 10,
            },
            editBook: {
                dialog: false,
                loading: false,
                tips: '',
                dialogVisible: false,
                formLabelWidth: '80px',
                disabled: true,
                timer: null,
                page: '',
                form: {
                    bookname: '',
                    id: '',
                    typeName: '',
                    typeId: '',
                    author: '',
                    press: '',
                    price: '',
                    isbn: '',
                    content: '',
                    scoreAvg: '',
                    scoreCount: ""
                },
                options: [],
                imageUrl: ''
            },
        }
    },
    methods: {
        findAllBooks() {
            this.loading = true;
            axios.get("http://localhost:8080/book?pageNum=" +
                this.pageData.currentPage + "&size=" + this.pageData.pageSize + "&bookName=" + this.search)
                .then(data => {
                    let res = data.data;
                    if (res.code == 1) {
                        this.tableData.data = res.data.list;
                        this.pageData.total = res.data.total;
                        this.pageData.currentPage = res.data.pageNum;
                        this.pageData.pageSize = res.data.pageSize;
                        this.loading = false;
                    } else {
                        this.$router.push('/error');
                    }
                })
                .catch();
        },
        handleCurrentChange(val) {
            this.pageData.currentPage = val;
            this.findAllBooks();
        },
        handleSizeChange(val) {
            this.pageData.pageSize = val;
            this.findAllBooks();
        },
        handleClose(done) {
            if (this.loading) {
                return
            }
            this.$confirm('确定要提交表单吗？')
                .then((_) => {
                    this.loading = true
                    this.timer = setTimeout(() => {
                        done()
                        setTimeout(() => { // 动画关闭需要一定的时间
                            this.loading = false
                        }, 400)
                    }, 2000)
                }).catch();
        },
        handleEdit(row) {
            this.editBook.dialogVisible = true;
            this.editBook.tips = "修改图书信息";
            let form = this.editBook.form;
            this.editBook.page = "edit";
            form.id = row.id;
            form.bookName = row.bookName;
            form.typeName = row.typeName;
            form.typeId = row.typeId;
            form.author = row.author;
            form.press = row.press;
            form.price = row.price;
            form.isbn = row.isbn;
            form.image = "http://localhost:8080/image/" + row.image;
            form.content = row.content;
        },
        handleDelete(row) {
            console.log(row);
            this.$confirm('此操作将永久删除' + row.typeName + ', 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            })
                .then(() => {
                    axios.post("http://localhost:8080/book/delete?id=" + row.id)
                        .then((data) => {
                            if (data.data.code === 1) {
                                this.$message({
                                    type: 'success',
                                    message: '删除成功!',
                                });
                            } else {
                                this.$message({
                                    type: 'info',
                                    message: '删除失败',
                                })
                            }
                        });
                })
                .catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除',
                    })
                })
        },
        modify() {
            const formData = JSON.stringify(this.editBook.form);
            axios({
                method: 'POST',
                url: 'http://localhost:8080/book/update?',
                headers: {
                    'Content-Type': 'application/json;charset=UTF-8'
                },
                data: formData,
            }).then()
                .catch();
        },
        handleAvatarSuccess(res, file) {
            this.imageUrl = URL.createObjectURL(file.raw);
        },
        beforeAvatarUpload(file) {
            const isJPG = file.type === 'image/jpeg';
            const isLt2M = file.size / 1024 / 1024 < 2;
            if (!isJPG) {
                this.$message.error('上传头像图片只能是 JPG 格式!')
            }
            if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 2MB!')
            }
            return isJPG && isLt2M
        },
        findAllTypes() {
            axios.get("http://localhost:8080/type/all")
                .then(data => {
                    let res = data.data;
                    if (res.code == 1) {
                        this.options = res.data;
                    } else {
                        this.$router.push('/error');
                    }
                })
                .catch();

        },
        search() {
            this.findAllBooks();
        }
    },
    mounted() {
        this.findAllBooks();
        this.findAllTypes();
    },
}
</script>

<style scoped>
.el-header {
    width: 100%;
    height: 40px;
    line-height: 40px;
}

.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.avatar-uploader .el-upload:hover {
    border-color: #409eff;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}

.avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>